package TCP.TCP通信程序练习5;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP接收数据 implements Runnable{
    private Socket s;
    public TCP接收数据(Socket s){
        this.s=s;
    }
    @Override
    public void run() {
        try {
            /*接收数据写到文本文件*/
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            /*解决名称冲突问题*/
            int count=0;
            File file = new File("day12\\数据接收[" + count + "].txt");
            while (file.exists()){
                count++;
                file=new File("day12\\数据接收[" + count + "].txt");
            }
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            String line;
            while ((line= br.readLine())!=null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }

            /*给出反馈*/
            BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bwServer.write("文件上传成功");
            bwServer.newLine();
            bwServer.flush();
            /*释放资源*/
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/*开始测试*/
class ServerDemo{
    public static void main(String[] args) throws IOException {
        /*创建服务器的Socket对象*/
        ServerSocket ss = new ServerSocket(10000);
        while (true){
            /*监听客户端连接，返回一个对应的Socket对象*/
            Socket s = ss.accept();
            /*为每一个客户端开启一个线程*/
            new Thread(new TCP接收数据(s)).start();
        }
    }
}














